import librosa
import torch
import numpy as np


def predict(model, audio_path, label_map, device):
    """预测文件标签"""
    y, sr = librosa.load(audio_path, sr=16000)
    y = np.pad(y, (0, max(0, 16000 - len(y))), 'constant')[:16000]
    mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)
    mfcc = torch.tensor(mfcc, dtype=torch.float32).unsqueeze(0).unsqueeze(0).to(device)

    with torch.no_grad():
        output = model(mfcc)
        _, predicted = output.max(1)
        label = list(label_map.keys())[list(label_map.values()).index(predicted.item())]
        return label
